package com.jmxcfc.blfsc.ssq.service.contract.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jmxcfc.blfsc.ssq.entity.SignContractSub;
import com.jmxcfc.blfsc.ssq.mapper.SignContractSubMapper;
import com.jmxcfc.blfsc.ssq.service.contract.ISignContractSubService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 上上签签署合同记录表 服务实现类
 * </p>
 *
 * @author pbs
 * @since 2024-09-08
 */
@Service
@Slf4j
public class SignContractSubServiceImpl extends ServiceImpl<SignContractSubMapper, SignContractSub> implements ISignContractSubService {

    /**
     * 判断是否存在签署记录
     *  signType=1(签署个人签名企业签名)时:
     需要进行两次签署,两次 签署的账号不一样,根据业务号、合同id、签署账号是否签署过,未签署过则用该账号进行签署
     * @param requestNo
     * @param signAccount
     * @param contractId
     * @return
     */
    @Override
    public boolean notExistSignContract(String requestNo, String signAccount, String contractId) {
        log.info("根据请求业务号requestNo:{},签署类型:【1:签署个人签名企业签名】,签署账号:{},合同id(contractId):{},查询表SSQ_SIGN_CONTRACT_SUB是否签署成功过", requestNo, signAccount, contractId);
        LambdaQueryWrapper<SignContractSub> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SignContractSub::getRequestNo, requestNo)
                .eq(SignContractSub::getSignerAccount, signAccount)
                .eq(SignContractSub::getContractId, contractId)
                .eq(SignContractSub::getErrno, "0");
        Boolean rt = count(queryWrapper) > 0 ? Boolean.FALSE : Boolean.TRUE;
        log.info("根据请求业务号requestNo:{},签署账号:{},合同id(contractId):{},判断不存在记录结果:{}", requestNo, signAccount, contractId, rt);
        return rt;
    }


    @Override
    public String queryLatestContractId(String requestNo) {
        LambdaQueryWrapper<SignContractSub> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(SignContractSub::getContractId)
                .eq(SignContractSub::getRequestNo, requestNo)
                .eq(SignContractSub::getErrno, "0")
                .orderByDesc(SignContractSub::getCreateTime);
        List<SignContractSub> signContractSubList = this.list(queryWrapper);
        String contractId = "";
        if (CollectionUtils.isNotEmpty(signContractSubList) && StringUtils.isNotBlank(signContractSubList.get(0).getContractId())) {
            contractId =  signContractSubList.get(0).getContractId();
        }
        return contractId;
    }


}
